package com.hthy.futures.ui.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;

import com.hthy.futures.AppContext;
import com.hthy.futures.R;
import com.hthy.futures.api.ST_TradeApi;
import com.hthy.futures.base.BaseFragment;
import com.hthy.futures.bean.Goods;
import com.hthy.futures.bean.OrderTicket;
import com.hthy.futures.bean.ht.BRealTimeQuotePush;
import com.hthy.futures.inter.BillEvent;
import com.hthy.futures.utils.DialogUtil;
import com.hthy.futures.utils.ErrorUtils;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.TDevice;
import com.vilyever.socketclient.SocketClient;

import net.hthy.bean.Trade;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import de.greenrobot.event.EventBus;

/**
 * 单据
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/6
 */

/**
 * 发现了一个奇怪的bug,在basefragment中是没事的，在baselistfragment中是有事的bu'n
 */

public class BillFragment extends BaseFragment {
    @Bind(R.id.view_tab_layout)
    TabLayout mViewTabLayout;
    @Bind(R.id.view_pager)
    ViewPager mViewPager;

    BillMardketFragment mBillMardketFragment;
    BillPendFragment mBillPendFragment;
    private String[] mBillTitle;


    protected SocketClient socketClient;


    private boolean isFromBillChild;
    private List<Goods> mGoodList = new ArrayList<>();
    private boolean isFromBillChild2 = false;


    @Override
    protected int getLayoutId() {
        return R.layout.frg_bill;
    }

    // 如果在新订单中生成成功的话，叫这个页面刷新
    public void onEventMainThread(BillEvent event) {
        if (event.isRefresh) {
            initData();
        } else {
            getOrderList();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        socketClient = ((AppContext) getActivity().getApplication()).getSocketClient();
        socketClient.registerSocketClientDelegate(this);

    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mBillTitle = getResources().getStringArray(R.array.array_me_billtitle);

        FragmentPagerAdapter mallPageAdapter = new TabFragmentAdapter(getActivity().getSupportFragmentManager());
        mViewPager.setAdapter(mallPageAdapter);
        mViewTabLayout.setupWithViewPager(mViewPager);
        mViewPager.setCurrentItem(0);


        // 在tablayout间加入竖线
        LinearLayout linearLayout = (LinearLayout) mViewTabLayout.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(getActivity(),
                R.drawable.layout_divider_vertical));
        // 分割线变短
        linearLayout.setDividerPadding(TDevice.dp2px(8));
    }


    @Override
    protected void initData() {
        super.initData();
        // 应该第一步获取商品的信息
        // 获取商品种类
        byte[] bytes = ST_TradeApi.searchGoods("2015");
        socketClient.sendData(bytes);
        isFromBillChild = true;
    }

    @Override
    protected void onResponse(SocketClient client, String responMes, byte[] subBytes) {
        super.onResponse(client, responMes, subBytes);
        LogUtils.e("是在billfragment" + responMes);

        //从查询交易商品获取
        if (isFromBillChild && responMes.indexOf("2016") != -1) {
            if (mGoodList != null && mGoodList.size() > 0) {
                mGoodList.clear();
            }
            try {
                Trade.QueryProductsResponseMsg queryProductsResponseMsg = Trade.QueryProductsResponseMsg.parseFrom(subBytes);
                List<Trade.UserProductsInfo> userProductsInfoList = queryProductsResponseMsg.getUserProductsInfoList();
                for (Trade.UserProductsInfo productsInfo : userProductsInfoList) {
                    Goods goods = new Goods();
                    goods.setSs_product_code(productsInfo.getSsProductCode());
                    goods.setSs_product_name(productsInfo.getSsProductName());
                    goods.setUi_buy_pips(productsInfo.getUiBuyPips() + "");
                    goods.setUi_sell_pips(productsInfo.getUiSellPips() + "");
                    goods.setUi_sl_pips(productsInfo.getUiSlPips() + "");
                    goods.setUi_tp_pips(productsInfo.getUiTpPips()+"");
                    goods.setDb_contract_size(productsInfo.getDbContractSize()+"");
                    goods.setDb_origin_margin(productsInfo.getDbOriginMargin() + "");
                    goods.setUi_margin_type(productsInfo.getUiMarginType()+"");
                    mGoodList.add(goods);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 接着才是请求订单相关的数据
            getOrderList();
        }

        // wei
        if (!isFromBillChild2) {
            return;
        }
        // 然后接着从返回的数据中截掉前面的37位，剩下就是json字符串内容。
        if (isFromBillChild2 && responMes.indexOf("2006") != -1) {
            DialogUtil.dimissDialog();
            try {
                Trade.QueryOrderResponseMsg queryOrderResponseMsg = Trade.QueryOrderResponseMsg.parseFrom(subBytes);

                if (queryOrderResponseMsg != null) {
                    int iErrorCode = queryOrderResponseMsg.getResponseMsg().getIErrorCode();
                    if (0 == iErrorCode) {

                        // 得进行json非空判断  TODO  就是在没有单据的情况下，有事后没有
                        /*if (JsonUtils.isEmpty(jsonObject.get("ORDERTICKET"))) {
                            //mErrorLayout.setErrorType(EmptyLayout.NODATA);
                            return;
                        }  */

                        List<Trade.UserOrderDetail> userOrderDetails = queryOrderResponseMsg.getOrderDetailList();   // 单据list
                        List<OrderTicket> mOrderTickets = new ArrayList<>();
                        for (Trade.UserOrderDetail userOrderDetail : userOrderDetails) {
                            OrderTicket orderTicket = new OrderTicket();
                            orderTicket.setDbExecuteSize(userOrderDetail.getDbExecuteSize()+"");
                            orderTicket.setDbOrderSize(userOrderDetail.getDbOrderSize()+"");
                            orderTicket.setOrderStatusValue(userOrderDetail.getOrderStatusValue()+"");   // 这个是单据的状态,是个枚举类型的
                            orderTicket.setOrderDirectionValue(userOrderDetail.getOrderDirectionValue() == 1 ? "b" : "s");  //
                            orderTicket.setSsProductCode(userOrderDetail.getSsProductCode() + "");
                            orderTicket.setDbTpPrice(userOrderDetail.getDbTpPrice()+"");
                            orderTicket.setDbSlPrice(userOrderDetail.getDbSlPrice()+"");
                            orderTicket.setLimitOrderType(userOrderDetail.getLimitOrderTypeValue()+"");  //
                            orderTicket.setDbHoldPrice(userOrderDetail.getDbHoldPrice()+"");
                            orderTicket.setSsExecuteTime(userOrderDetail.getSsExecuteTime());
                            orderTicket.setUiOrderCloseStatus(userOrderDetail.getUiOrderCloseStatus() == 49 ? "1" : "2"); //
                            orderTicket.setUiOrderUid(userOrderDetail.getUiOrderUid()+"");
                            orderTicket.setDbTotalSwap(userOrderDetail.getDbTotalSwap()+"");
                            orderTicket.setDbOrderPrice(userOrderDetail.getDbOrderPrice()+"");
                            orderTicket.setOrderTime(userOrderDetail.getOrderTime());

                            mOrderTickets.add(orderTicket);
                        }

                        // 把商品屬性賦值給orderticket
                        for (OrderTicket orderTicket : mOrderTickets) {
                            for (Goods goods : mGoodList) {
                                if ((goods.getSs_product_code().equals(orderTicket.getSsProductCode()))) {
                                    // 这个时候赋值操作
                                    orderTicket.buyPriceSpreed = goods.getUi_buy_pips();
                                    orderTicket.sellPriceSpreed = goods.getUi_sell_pips();

                                    orderTicket.order_s_spread = goods.getUi_sl_pips();
                                    orderTicket.order_y_spread = goods.getUi_tp_pips();

                                    orderTicket.contractUnit = goods.getDb_contract_size();  // 合约单位

                                    // 为了计算保证金，得从goods里面得到初始保证金以及合约单位
                                    orderTicket.initGuaranteeMoney = goods.getDb_origin_margin(); // 初始保障金
                                    orderTicket.moneyHoldType = goods.getUi_margin_type(); // 保证金类型
                                }
                            }
                        }
                        mBillMardketFragment.setOrderTickets(mOrderTickets);
                        mBillPendFragment.setOrderTickets(mOrderTickets);

                        isFromBillChild2 = false;
                    } else {
                        ErrorUtils.showToast(getActivity(), iErrorCode + "");
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                LogUtils.e("BillFragment", "exception" + e);
                getOrderList();
            }

        }
    }

    //请求订单相关的数据
    private void getOrderList() {
       /* String historyData = ST_TradeApi.searchGoods("2005");  // ordeericket
        socketClient.sendString(historyData);*/
        byte[] baseStr2 = ST_TradeApi.searchGoods("2005");
        socketClient.sendData(baseStr2);

        DialogUtil.showDialog(getActivity());
        isFromBillChild = false;
        isFromBillChild2 = true;
    }

    public void setRealTimeQuotePushes(List<BRealTimeQuotePush> bRealTimeQuotePushes) {
        // 直接设置给子孩子
        if (mBillMardketFragment != null) {
            mBillMardketFragment.setRealTimeQuotePush(bRealTimeQuotePushes);
        }
        if (mBillPendFragment != null) {
            mBillPendFragment.setRealTimeQuotePush(bRealTimeQuotePushes);
        }
    }

    public class TabFragmentAdapter extends FragmentPagerAdapter {

        public TabFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Bundle bundle = new Bundle();
            switch (position) {
                case 0:// 发布中
                    if (mBillMardketFragment == null) {
                        mBillMardketFragment = new BillMardketFragment();
                    }
                    bundle.putInt(getString(R.string.intent_key_type), 0);
                    mBillMardketFragment.setArguments(bundle);
                    return mBillMardketFragment;
                case 1://  下架
                    if (mBillPendFragment == null) {
                        mBillPendFragment = new BillPendFragment();

                    }
                    bundle.putInt(getString(R.string.intent_key_type), 1);
                    mBillPendFragment.setArguments(bundle);
                    return mBillPendFragment;
                default:
                    break;
            }
            return null;
        }

        @Override
        public int getCount() {
            if (mBillTitle != null) {
                return mBillTitle.length;
            }
            return 0;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mBillTitle[position];
        }
    }

}
